const PORT1 = "/api";
import { baseURL } from "./env.js";
import { tokenBear } from "../constants/apiConstants";
import Router from "./Router.js";

export const umodal = (title = "确定要删除吗?") =>
  new Promise((resolve, reject) =>
    uni.showModal({
      title,
      success(res) {
        resolve(res.confirm);
      },
      fail() {
        reject("error");
      },
    })
  );

export const uModal = (title = "确定要删除吗?") =>
  new Promise((resolve, reject) =>
    uni.showModal({
      title,
      success(res) {
        resolve(res.confirm);
      },
      fail() {
        reject("error");
      },
    })
  );

export const uGetStorageSync = (key) => uni.getStorageSync(key);
export const uSetStorageSync = (key, value) => uni.setStorageSync(key, value);
export const uRemoveStorageSync = (key) => uni.removeStorageSync(key);

export const utoast = (
  title = "操作成功!",
  icon = "success",
  duration = 2000
) =>
  new Promise((resolve, reject) =>
    uni.showToast({
      title,
      icon,
      duration,
      success() {
        resolve("success");
      },
      fail() {
        reject("error");
      },
    })
  );

export const uToast = (
  title = "操作成功!",
  icon = "success",
  duration = 2000
) =>
  new Promise((resolve, reject) =>
    uni.showToast({
      title,
      icon,
      duration,
      success() {
        resolve("success");
      },
      fail() {
        reject("error");
      },
    })
  );

export const uploadImage = async () => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        console.log("res.tempFilePaths", res.tempFilePaths);
        res.tempFilePaths.forEach((e) => {
          uni.uploadFile({
            url: baseURL + PORT1 + "/Tools/UploadFiles",
            filePath: e,
            name: "file",
            header: {
              "content-type": "multipart/form-data; charset=utf-8",
              token: tokenBear,
            },
            success: (uploadFileRes) => {
              var jsonData = JSON.parse(uploadFileRes.data);
              if (jsonData.code == 0) {
                console.log("jsonData", jsonData);
                resolve(jsonData.data.src);
              } else {
                reject("图片上传失败");
              }
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
        //this.imageList = this.imageList.concat(res.tempFilePaths);
      },
      fail: (err) => {
        console.log("err: ", err);
        // #ifdef APP-PLUS
        if (err["code"] && err.code !== 0 && this.sourceTypeIndex === 2) {
          this.checkPermission(err.code);
        }
        // #endif
        // #ifdef MP
        if (err.errMsg.indexOf("cancel") !== "-1") {
          return;
        }
        uni.getSetting({
          success: (res) => {
            let authStatus = false;
            switch (this.sourceTypeIndex) {
              case 0:
                authStatus = res.authSetting["scope.camera"];
                break;
              case 1:
                authStatus = res.authSetting["scope.album"];
                break;
              case 2:
                authStatus =
                  res.authSetting["scope.album"] &&
                  res.authSetting["scope.camera"];
                break;
              default:
                break;
            }
            if (!authStatus) {
              uni.showModal({
                title: "授权失败",
                content:
                  "Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限",
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                },
              });
            }
          },
        });
        // #endif
      },
    });
  });
};

export const uploadFile = async (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseURL + PORT1 + "/Tools/UploadFiles",
      filePath,
      name: "file",
      header: {
        "content-type": "multipart/form-data; charset=utf-8",
        token: tokenBear,
      },
      success: (uploadFileRes) => {
        var jsonData = JSON.parse(uploadFileRes.data);
        if (jsonData.code == 0) {
          console.log("jsonData", jsonData);
          resolve(jsonData.data.src);
        } else {
          reject("文件上传失败");
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

export const uShowLoading = async (title = "加载中。。。") =>
  uni.showLoading({
    title,
  });

export const uHideLoading = async () => uni.hideLoading();

export const uNavigateTo = (url) =>
  uni.navigateTo({
    url,
  });

export const uReLaunch = (url) =>
  uni.reLaunch({
    url,
  });

export const uRedirectTo = (url) =>
  uni.redirectTo({
    url,
  });

export const uNavigateBack = (delta = 1) =>
  uni.navigateBack({
    delta,
  });

export const uSwitchTab = (url) =>
  uni.switchTab({
    url,
  });

export const uSetNavigationBarTitle = (title) =>
  uni.setNavigationBarTitle({
    title,
  });

export const uPreviewImage = (url) =>
  uni.previewImage({
    urls: [url],
  });

export const uScanCode = () =>
  new Promise((resolve, reject) => {
    uni.authorize({
      scope: "scope.camera",
      success() {
        uni.scanCode({
          success(res) {
            if (res.result) {
              // 扫描成功，处理二维码内容
              resolve(res.result);
              // 这里可以进行后续操作，如跳转页面、显示信息等
            } else {
              reject("授权失败！");
            }
          },
          fail() {
            // 调用相机失败
            uni.showToast({
              title: "调用相机失败",
              icon: "none",
            });
          },
        });
      },
      fail() {
        // 用户拒绝授权
        uni.showToast({
          title: "您拒绝了授权",
          icon: "none",
        });
        reject("您拒绝了授权");
      },
    });
  });

/**
 * 订阅推送消息
 * @param tmplIds 模板ID
 */
export function uRequestSubscribeMessage(tmplIds = []) {
  uni.requestSubscribeMessage({
    tmplIds: tmplIds, // 数组，最多3个订阅
    success(res) {
      console.log("订阅消息结果", res);
      // 处理订阅消息的结果
    },
    error() {},
  });
}

export function setArray(array1, array2) {
  const idSet = new Set(array1.map((item) => item.id)); // 提取 array1 中的 id 到 Set
  array2.forEach((item) => {
    if (!idSet.has(item.id)) {
      array1.push(item);
      idSet.add(item.id); // 将新添加的 id 加入 Set 中
    }
  });
}

/**
 * 万能路由
route(Object)
此为一个路由跳转方法，内部是对uni多个路由跳转api的封装，更方便使用
Object参数说明：
参数名	类型	默认值	是否必填	说明
type	String	navigateTo	false	navigateTo对应uni.navigateTo，redirectTo对应uni.redirectTo，switchTab对应uni.switchTab，reLaunch对应uni.reLaunch，navigateBack或back对应uni.navigateBack
url	String	-	false	type为navigateTo，redirectTo，switchTab，reLaunch时为必填
delta	Number	1	false	type为navigateBack时用到，表示返回的页面数
params	Object	-	false	传递的对象形式的参数，如{name: 'lisa', age: 18}
 */
export const uRoute = (options = {}, params = {}) =>
  new Router().route(options, params);

export const uNavigateToWithParams = (url, params) =>
  uRoute({
    type: "navigateTo",
    url,
    params,
  });

export const uRedirectToWithParams = (url, params) =>
  uRoute({
    type: "redirectTo",
    url,
    params,
  });

/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {*} func  要执行的回调函数
 * @param {*} wait 延时的时间
 * @param {*} immediate  是否立即执行
 */
export function uDebounce(func, wait = 500, immediate = false) {
  // 清除定时器
  if (timeout !== null) clearTimeout(timeout);
  // 立即执行，此类情况一般用不到
  if (immediate) {
    const callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) typeof func === "function" && func();
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    timeout = setTimeout(() => {
      typeof func === "function" && func();
    }, wait);
  }
}

let timer;
let flag;
/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
export function uThrottle(func, wait = 2500, immediate = true) {
  if (immediate) {
    if (!flag) {
      flag = true;
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === "function" && func();
      timer = setTimeout(() => {
        flag = false;
      }, wait);
    }
  } else if (!flag) {
    flag = true;
    // 如果是非立即执行，则在wait毫秒内的结束处执行
    timer = setTimeout(() => {
      flag = false;
      typeof func === "function" && func();
    }, wait);
  }
}
